<template>
  <div class="app-container">
    <pro-table
      ref="tableRef"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :total="total"
      :show-selection="false"
      row-key="id"
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @query="handleQuery"
      @add="handleAdd"
      @refresh="getList"
    >
      <template #toolbar-left>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增权限</el-button>
      </template>

      <template #type="{ row }">
        <el-tag :type="row.type === 1 ? 'primary' : 'success'">
          {{ row.type === 1 ? '菜单权限' : '按钮权限' }}
        </el-tag>
      </template>

      <template #action="{ row }">
        <el-button type="primary" link @click="handleEdit(row)">
          <el-icon><Edit /></el-icon>编辑
        </el-button>
        <el-button type="success" link @click="handleAdd(row)">
          <el-icon><Plus /></el-icon>新增
        </el-button>
        <el-button type="danger" link @click="handleDelete(row)">
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </template>
    </pro-table>

    <!-- 权限表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增权限' : '编辑权限'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="上级权限">
          <el-tree-select
            v-model="form.parentId"
            :data="authTree"
            placeholder="请选择上级权限"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio :label="1">菜单权限</el-radio>
            <el-radio :label="2">按钮权限</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="form.code" placeholder="请输入权限标识">
            <template #append v-if="form.type === 2">:{{ getButtonPermission() }}</template>
          </el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import ProTable from '@/components/ProTable/index.vue';
import {
  getAuthList,
  getAuthTree,
  addAuth,
  updateAuth,
  deleteAuth,
  updateAuthStatus
} from '@/api'

// 列配置
const columns = [
  {
    prop: 'name',
    label: '权限名称',
    minWidth: '180',
    search: true
  },
  {
    prop: 'code',
    label: '权限标识',
    minWidth: '180'
  },
  {
    prop: 'type',
    label: '权限类型',
    width: '120',
    align: 'center',
    search: true,
    searchType: 'select',
    options: [
      { label: '菜单权限', value: 1 },
      { label: '按钮权限', value: 2 }
    ],
    slot: 'type'
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    align: 'center',
    search: true,
    searchType: 'select',
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ],
    render: 'StatusSwitch'
  },
  {
    prop: 'sort',
    label: '排序',
    width: '80',
    align: 'center'
  }
]

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const authTree = ref([])

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const form = ref({
  parentId: 0,
  name: '',
  code: '',
  type: 1,
  sort: 0,
  status: 1,
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限标识', trigger: 'blur' },
    { pattern: /^[a-z][a-z:]*[a-z]$/, message: '权限标识只能包含小写字母和冒号', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 获取按钮权限标识
const getButtonPermission = () => {
  const buttons = ['add', 'edit', 'delete', 'export', 'import']
  return buttons.join('|')
}

// 获取列表数据
const getList = async (params) => {
  loading.value = true
  try {
    const [listRes, treeRes] = await Promise.all([
      getAuthList(params),
      getAuthTree()
    ])
    tableData.value = listRes.data
    authTree.value = [{
      id: 0,
      name: '顶级权限',
      children: treeRes.data
    }]
  } catch (error) {
    console.error('获取权限列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = (params) => {
  getList(params)
}

// 新增权限
const handleAdd = (row = null) => {
  dialogType.value = 'add'
  form.value = {
    parentId: row ? row.id : 0,
    name: '',
    code: '',
    type: 1,
    sort: 0,
    status: 1,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addAuth(form.value)
          ElMessage.success('添加成功')
        } else {
          await updateAuth(form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 删除权限
const handleDelete = (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage.warning('请先删除子权限')
    return
  }

  ElMessageBox.confirm(
    '确认删除该权限吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteAuth(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
  background-color: #f5f7fa;
}

:deep(.el-tree-select) {
  width: 100%;
}

:deep(.el-input-number) {
  width: 100%;
}

.dialog-footer {
  padding-top: 20px;
  text-align: right;
}

:deep(.el-button) {
  margin-left: 8px;
}

:deep(.el-icon) {
  margin-right: 4px;
}
</style> 